package com.jarveis.frame.task;

import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;

/**
 * 处理任务的线程
 * 
 * @author liuguojun
 */
public final class TaskThread extends Thread {

	private static Logger logger = Logger.getLogger(TaskThread.class);

	/**
	 * -1:stop, 0:wait, 1:running
	 */
	private AtomicInteger workState = new AtomicInteger(0);
	private int idleSecond = 0;
	private ITask task;

	/**
	 * 设置任务对象
	 * 
	 * @param task
	 */
	public void setTask(ITask task) {
		this.task = task;
	}

	/**
	 * 设置空闲的时间
	 * 
	 * @param second
	 */
	void setIdleSecond(int second) {
		this.idleSecond = second;
	}

	/**
	 * 获取空闲的时间
	 * 
	 * @return int
	 */
	int getIdleSecond() {
		return this.idleSecond;
	}

	/**
	 * 获取工作状态
	 * 
	 * @return int
	 */
	int getWorkState() {
		return workState.get();
	}

	/**
	 * 通知线程结束
	 */
	public synchronized void notifyStop() {
		workState.decrementAndGet();
		notify();
	}

	/**
	 * 开始任务
	 */
	public synchronized void startTask() {
		workState.incrementAndGet();
		notify();
	}

	public synchronized void run() {
		try {
			while (workState.get() > -1) {
				if (workState.get() == 0) {
					// 如果当前线程空闲，则等待新的任务
					wait();
				} else {
					if (task != null) {
						// 执行任务
						task.execute();
						if (task.getTaskInfo() != null) {
							task.getTaskInfo().setStatus(ITask.Status.Sleep);
						}
						task = null;
					}
					workState.decrementAndGet();
				}
			}
		} catch (InterruptedException ex) {
			if (task != null && task.getTaskInfo() != null
					&& task.getTaskInfo().getStatus() == ITask.Status.Start) {
				task.getTaskInfo().setStatus(ITask.Status.Sleep);
			}
			logger.error(ex.getMessage(), ex);
		}
	}
}
